<template>
  <el-dialog
    :title="
      dialogType === 'add' ? 'Add Client' : 'Modify Client'
    "
    v-model="dialogVisible"
    width="800px"
    destroy-on-close
  >
    <div class="client-form">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="180px"
        label-position="left"
      >
        <div class="form-section">
          <div class="section-title">Client Information</div>
          
          <el-form-item label="Client Name" prop="clientName" required>
            <el-input
              v-model="form.clientName"
              placeholder="Please enter client name"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>

          <el-form-item label="Client Email" prop="clientEmail" required>
            <el-input
              v-model="form.clientEmail"
              placeholder="Please enter client email"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>

          <el-form-item label="Country/Region" prop="countryRegion">
            <el-select
              v-model="form.countryRegion"
              placeholder="Please select country/region"
              style="width: 100%"
              :disabled="dialogType === 'edit'"
            >
              <el-option
                v-for="item in countryOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="Organization Address"
            prop="organizationAddress"
          >
            <el-input
              v-model="form.organizationAddress"
              placeholder="Please enter organization address"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>

          <el-form-item
            label="Organization Email"
            prop="organizationEmail"
          >
            <el-input
              v-model="form.organizationEmail"
              placeholder="Please enter organization email"
              show-word-limit
              maxlength="100"
              :disabled="dialogType === 'edit'"
            />
          </el-form-item>
        </div>

        <div class="form-section">
          <div class="section-title">Admin Information</div>
          
          <el-form-item label="Admin Name" prop="adminName" required>
            <el-input
              v-model="form.adminName"
              placeholder="Please enter admin name"
              show-word-limit
              maxlength="100"
            />
          </el-form-item>

          <el-form-item label="Admin Email" prop="adminEmail">
            <el-input
              v-model="form.adminEmail"
              placeholder="Please enter admin email"
              show-word-limit
              maxlength="100"
              :disabled="dialogType === 'edit'"
            />
          </el-form-item>

          <el-form-item label="Admin Mobile" prop="adminMobile">
            <el-input
              v-model="form.adminMobile"
              placeholder="Please enter admin mobile"
              show-word-limit
              maxlength="20"
              @input="handleAdminMobileInput"
            />
          </el-form-item>
        </div>


      </el-form>
    </div>

    <template #footer>
      <div class="flex justify-end gap-2">
        <el-button @click="dialogVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm">Submit</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
// 客户编辑对话框
// 职责：
// - 编辑客户/组织/管理员信息
// - 新增/编辑时的字段与校验管理
// - 校验通过后向父组件回传数据
import { ref, reactive, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  formData: {
    type: Object,
    default: () => ({})
  },
  dialogType: {
    type: String,
    default: "add" // 'add' 或 'edit'
  }
});

const emit = defineEmits(["update:visible", "submit-success"]);

// 表单实例与显隐
const formRef = ref<FormInstance>();
const dialogVisible = ref(props.visible);

// 表单数据
const form = reactive({
  id: "",
  clientName: "",
  clientEmail: "",
  countryRegion: "",
  organizationEmail: "",
  organizationAddress: "",
  adminName: "",
  adminEmail: "",
  adminMobile: ""
});

// 验证规则
const rules = reactive<FormRules>({
  clientName: [
    {
      required: true,
      message: "Please enter client name",
      trigger: "blur"
    },
    {
      max: 100,
      message: "Client name cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  clientEmail: [
    {
      required: true,
      message: "Please enter client email",
      trigger: "blur"
    },
    {
      type: "email",
      message: "Please enter valid email format",
      trigger: "blur"
    },
    {
      max: 100,
      message: "Client email cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  countryRegion: [
    {
      required: true,
      message: "Please select country/region",
      trigger: "change"
    }
  ],
  organizationAddress: [
    {
      max: 100,
      message: "Organization address cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  organizationEmail: [
    {
      type: "email",
      message: "Please enter valid email format",
      trigger: "blur"
    },
    {
      max: 100,
      message: "Organization email cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  adminName: [
    {
      required: true,
      message: "Please enter admin name",
      trigger: "blur"
    },
    {
      max: 100,
      message: "Admin name cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  adminEmail: [
    {
      type: "email",
      message: "Please enter valid email format",
      trigger: "blur"
    },
    {
      max: 100,
      message: "Admin email cannot exceed 100 characters",
      trigger: "blur"
    }
  ],
  adminMobile: [
    {
      pattern: /^\d*$/,
      message: "管理员手机号只能输入数字",
      trigger: "blur"
    },
    {
      max: 20,
      message: "Admin mobile cannot exceed 20 characters",
      trigger: "blur"
    }
  ],

});

// 国家/地区选项
const countryOptions = ref([
  { label: "Sweden", value: "Sweden" },
  { label: "United States", value: "United States" },
  { label: "China", value: "China" },
  { label: "Germany", value: "Germany" },
  { label: "France", value: "France" },
  { label: "United Kingdom", value: "United Kingdom" },
  { label: "Japan", value: "Japan" },
  { label: "South Korea", value: "South Korea" },
  { label: "Australia", value: "Australia" },
  { label: "Canada", value: "Canada" }
]);

// 处理管理员手机号输入，只允许数字
const handleAdminMobileInput = (value: string) => {
  // 过滤非数字字符
  const numericValue = value.replace(/\D/g, '');
  form.adminMobile = numericValue;
};

// 重置表单
const resetForm = () => {
  form.id = "";
  form.clientName = "";
  form.clientEmail = "";
  form.countryRegion = "";
  form.organizationEmail = "";
  form.organizationAddress = "";
  form.adminName = "";
  form.adminEmail = "";
  form.adminMobile = "";
};

// 监听可见性：父传入 visible 改变时同步对话框显隐
watch(
  () => props.visible,
  val => {
    dialogVisible.value = val;
  }
);

// 监听对话框可见性：同步回父组件
watch(
  () => dialogVisible.value,
  val => {
    emit("update:visible", val);
  }
);

// 监听传入的表单数据：编辑态回填
watch(
  () => props.formData,
  val => {
    if (Object.keys(val).length > 0) {
      // 重置表单
      resetForm();

      // 设置表单数据
      form.id = val.id || "";
      form.clientName = val.clientName || "";
      form.clientEmail = val.clientEmail || "";
      form.countryRegion = val.countryRegion || "";
      form.organizationEmail = val.organizationEmail || "";
      form.organizationAddress = val.organizationAddress || "";
      form.adminName = val.adminName || "";
      form.adminEmail = val.adminEmail || "";
      form.adminMobile = val.adminMobile || "";
    }
  },
  { immediate: true, deep: true }
);

// 提交表单：校验通过后回传给父组件
const submitForm = async () => {
  if (!formRef.value) return;

  await formRef.value.validate((valid, fields) => {
    if (valid) {
      // 构建提交数据
      const submitData = {
        ...form,
        isAdd: props.dialogType === "add"
      };

      emit("submit-success", submitData);
    }
  });
};
</script>

<style lang="scss" scoped>
.client-form {
  .form-section {
    margin-bottom: 24px;
    
    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      margin-bottom: 16px;
      padding-bottom: 8px;
      border-bottom: 1px solid #eee;
    }
  }
}
</style>
